package com.zhangyue.wqercs.recyclerviewdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    List<String> list = new ArrayList<>();
    private MyRecyclerAdapter myRecyclerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取RecycleView控件
        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        for(int i=0;i<20;i++){
            list.add("item:"+i);
        }
//        GridLayoutManager
//        StaggeredGridLayoutManager
        //给RecyclerView设置布局管理器（这是一个很重要的功能，不同的管理器可以出现不同的布局）
        //LinearLayoutManager是一个线性布局管理器。通过它可以实现水平的ListView或者垂直的ListView
//        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setLayoutManager(new GridLayoutManager(this,3));
//        recyclerView.setLayoutManager(
//                new StaggeredGridLayoutManager(3,LinearLayoutManager.VERTICAL));
        //给RecycleView设置Adapter
        myRecyclerAdapter = new MyRecyclerAdapter(list);
        recyclerView.setAdapter(myRecyclerAdapter);
        //给recycerView创建一个装饰，例如分割线
        recyclerView.addItemDecoration(new MyItemDecoration());
        MyItemTouchHelperCallback callback = new MyItemTouchHelperCallback(myRecyclerAdapter);
        ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(recyclerView);
    }

    public void addItem(View view) {
        //修改集合中数据
        list.add(1,"addItem");
        //recycleView可以控制到只更新每个下标，从而比ListView的全局更新性能更优化
        myRecyclerAdapter.notifyItemInserted(1);
    }
    //同理删除
    public void removeItem(View view) {
        list.remove(1);
        myRecyclerAdapter.notifyItemRemoved(1);
    }
}
